<template>
  <div>
      <h2>商品购物车</h2>
      <table border="1" cellspacing='0'>
          <tr>
              <th>
                  <input type="checkbox" v-model='is_sel' @click='selAll'>
              </th>
              <th>序号</th>
              <th>名称</th>
              <th>单价</th>
              <th>数量</th>
              <th>小计</th>
              <th>操作</th>
          </tr>
          <tr v-for="(data,index) in datas">
              <td>
                  <input type="checkbox" v-model='data.sel'>
              </td>
              <td>{{index + 1}}</td>
              <td>{{data.name}}</td>
              <td>¥{{data.price}}</td>
              <td>
                  <button @click='data.num > 1 ? data.num--:1'>-</button>
                  <input type="text" v-model='data.num' style='width:20px'>
                  <button @click='data.num > 19 ? 20: data.num++'>+</button>
                  </td>
              <td>¥{{data.price * data.num}}</td>
              <td>
                  <button @click='delFn(index)'>删除</button>
              </td>
          </tr>
          <tr>
              <td colspan="7">
                  总价： ¥{{totalPrice}} &nbsp;
                  总数量： {{totalSum}}
              </td>
          </tr>
          <tr>
              <td colspan="7">
                  <button @click='delAll'>清空</button>
              </td>
          </tr>
        
      </table>
  </div>
</template>

<script>
export default {
    name: 'Cart',
    data(){
        return {
            datas: [
                {"name":"可乐","price":5,"num":5,"sel":false},
                {"name":"雪碧","price":10,"num":6,"sel":false},
                {"name":"橙汁","price":8,"num":8,"sel":false},
            ],
            is_sel: false
        }
    },
    methods: {
        //删除单条
        delFn(i){
            //删除？
            this.datas.splice(i,1)
        },
        //删除全部 清空
        delAll(){
            this.datas = []
        },
        //全选
        selAll(){
            //根据全选框 进行所有数据复选框操作
            this.datas.forEach(item =>{
                // if (this.is_sel === false) {
                //     item.sel = true
                // } else {
                //     item.sel = false
                // }
                item.sel = !this.is_sel 
            })
        }
    },
    //计算属性
    computed: {
        //1.计算总价
        totalPrice(){
            //数组中选中的数据中 单价*数量 相加
            let sums = 0
            this.datas.forEach(item =>{
                //item
                if(item.sel){
                      sums +=  item.price * item.num
                }
            })
            return sums
        },
        //2. 计算总数量
        totalSum(){
            let sums = 0
            this.datas.forEach(item =>{
                //item
                if(item.sel){
                      sums +=  item.num
                }
            })
            return sums
        }
    }
}
</script>

<style>

</style>